<template>
  <zeda-dialog
    v-model="visible"
    :title="(id <= 0 ? '新建' : '编辑') + ''"
    width="600px"
    :before-close="handleClose"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <form-button
      slot="footer"
      :loading="loading"
      :submitText="'确定'"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
  </zeda-dialog>
</template>

<script>
import {
  add,
  edit,
  detail,
  getNonOfficialRoomList,
  getRegionDeptList,
} from "@/api/energyConservation/feiset.js";
import CascaderSelect from "@/components/Select/CascaderSelect";
import FormButton from "@/components/FormButton";
import {
  deepClone,
  replaceDigit,
  replaceInteger,
  dealElectricity,
} from "@/utils/index";

export default {
  dicts: [],
  components: {
    FormButton,
    CascaderSelect,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false, // 按钮加载中判断
      showRoomArr: [],
      showDeptArr: [],
      apsForm: {
        formRef: "form",
        formData: {},
        labelWidth: "auto",
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 1,
              middle: true,
            },
            rules: {
              deptId: [
                {
                  required: true,
                  message: "请选择适用区域",
                  trigger: "change",
                },
              ],
              roomId: [
                {
                  required: true,
                  message: "请选择机构名称",
                  trigger: "change",
                },
              ],
              year: [
                {
                  required: true,
                  message: "请选择年份",
                  trigger: "change",
                },
              ],
              month: [
                {
                  required: true,
                  message: "请选择月份",
                  trigger: "change",
                },
              ],
              revenue: [
                {
                  required: true,
                  message: "请输入正确的营收",
                  trigger: "blur",
                },
              ],
              natualGas: [
                {
                  required: false,
                  message: "请输入正确的燃气量",
                  trigger: "blur",
                },
              ],
            },
          },
          properties: {
            deptId: {
              label: "适用区域",
              render: (h) => {
                let that = this;
                let arr = [...that.showDeptArr];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().deptId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择适用区域",
                        value: valNum,
                        clearable: true,
                        filterable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("deptId", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            roomId: {
              label: "机构名称",
              render: (h) => {
                let that = this;
                let arr = [...that.showRoomArr];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().roomId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择机构名称",
                        value: valNum,
                        clearable: true,
                        filterable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("roomId", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            year: {
              label: "年份",
              typeName: "el-date-picker",
              type: "year",
              size: "small",
              placeholder: "选择年份",
              "value-format": "yyyy",
            },
            month: {
              label: "月份",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                arr = [
                  {
                    label: "一月",
                    value: 1,
                  },
                  {
                    label: "二月",
                    value: 2,
                  },
                  {
                    label: "三月",
                    value: 3,
                  },
                  {
                    label: "四月",
                    value: 4,
                  },
                  {
                    label: "五月",
                    value: 5,
                  },
                  {
                    label: "六月",
                    value: 6,
                  },
                  {
                    label: "七月",
                    value: 7,
                  },
                  {
                    label: "八月",
                    value: 8,
                  },
                  {
                    label: "九月",
                    value: 9,
                  },
                  {
                    label: "十月",
                    value: 10,
                  },
                  {
                    label: "十一月",
                    value: 11,
                  },
                  {
                    label: "十二月",
                    value: 12,
                  },
                ];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().month;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择月份",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("month", value);
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            revenue: {
              label: "营收",
              render: (h) => {
                let that = this;
                let unit = "元";
                let a = (
                  <el-input
                    value={that.$refs?.form?.getFieldsValue().revenue}
                    size="small"
                    placeholder="请输入营收"
                    clearable
                    maxlength="12"
                    onInput={(val) => that.replaceDigitDeal(val, 3, "revenue")}
                  >
                    <template slot="append">{unit}</template>
                  </el-input>
                );
                return a;
              },
            },
            natualGas: {
              label: "燃气量",
              render: (h) => {
                let that = this;
                let unit = "立方米";
                let a = (
                  <el-input
                    value={that.$refs?.form?.getFieldsValue().natualGas}
                    size="small"
                    placeholder="请输入燃气量"
                    clearable
                    maxlength="12"
                    onInput={(val) =>
                      that.replaceDigitDeal(val, 3, "natualGas")
                    }
                  >
                    <template slot="append">{unit}</template>
                  </el-input>
                );
                return a;
              },
            },
          },
        },
      },
    };
  },
  watch: {
    visible(value) {
      if (value) {
        this.getgetNonOfficialRoomList();
        this.requestgetRegionDeptList();
        setTimeout(() => {
          this.$refs?.form?.setFieldValue("natualGas", 0); // 默认设置燃气量为0
        }, 200); // 新增默认选择舟山市本级
        if (String(this.id).length > 0) {
          setTimeout(() => {
            this.getInfo();
          }, 400);
        }
      }
    },
  },
  methods: {
    getgetNonOfficialRoomList() {
      this.showRoomArr = [];
      getNonOfficialRoomList({})
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.data ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.name,
                value: item?.id,
              };
              this.showRoomArr.push(obj);
            });
          }
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    requestgetRegionDeptList() {
      this.showDeptArr = [];
      getRegionDeptList({})
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.data ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.deptName,
                value: item?.deptId,
              };
              this.showDeptArr.push(obj);
            });
            if (!this.id) {
              this.$refs?.form?.setFieldValue("deptId", 103); //需要确认线上环境的接口返回的ID是不是一样的
            }
          }
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    getInfo() {
      detail(this.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data || {};
          let result = {};
          const dateStr = newData?.statisticTime ?? "";
          const [year, month] = dateStr.split("-").slice(0, 2);
          result.year = year;
          result.month = Number(month);
          result.revenue = newData?.revenue ?? 0;
          result.natualGas = newData?.natualGas ?? 0;
          result.roomId = newData?.roomId ?? 0;
          result.deptId = newData?.deptId ?? 0;
          this.$refs?.form?.setFieldsValue(result);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    submit() {
      const info = this.$refs.form.getFieldsValue();
      // 处理表单的数据
      const data = {
        id: this.id,
        deptId: info.deptId,
        roomId: info.roomId,
        year: info.year,
        month: info.month,
        natualGas: info.natualGas,
        revenue: info.revenue,
      };
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.id) {
            this.editRequest(data);
          } else {
            this.addRequest(data);
          }
        } else {
          return false;
        }
      });
    },
    addRequest(data) {
      add(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    editRequest(data) {
      edit(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    handleClose(status) {
      this.$refs["form"].resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
    /* 输入限制 */
    // 限制输入保留小数位数
    replaceDigitDeal(val, dit, flage) {
      let result = replaceDigit(val, dit);
      this.$refs?.form?.setFieldValue(flage, result);
    },
    // 限制输入整数
    replaceIntegerDeal(val, flage) {
      let result = replaceInteger(val);
      this.$refs?.form?.setFieldValue(flage, result);
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
  .map {
    display: flex;
    .el-input {
      margin-right: 10px;
    }
  }
}
</style>
